import services from '@/services/demo';
import { getBillAll, getTransactionConfigAll, deleteBill } from '@/services/bill';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, message, Upload, Card, Descriptions } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const props: UploadProps = {
  name: 'file',
  action: 'https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

const TableList: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.UserInfo[]>([]);
  const [transactionConfigAllData, setTransactionConfigAllData] = useState<any>([]);
  const [sumData, setSumData] = useState<any>({
    alipay_expenditure_total: 0,
    alipay_income_total: 0,
    expenditure_total: 0,
    inCome_total: 0,
    not_counting_total: 0,
    wechat_expenditure_total: 0,
    wechat_income_total: 0,
  });
  const columns: ProDescriptionsItemProps<API.UserInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tip: 'id 是唯一的 key',
      ellipsis: true,
      copyable: true,
      width: 150
    },
    {
      title: '交易日期',
      width: 150,
      dataIndex: 'payTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '交易日期',
      width: 150,
      dataIndex: 'payTime',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '交易类型',
      width: 100,
      dataIndex: 'transactionTypeValue',
      valueType: 'select',
      valueEnum: transactionConfigAllData,
    },
    {
      title: '交易人',
      width: 150,
      dataIndex: 'trader',
      ellipsis: true,
      search: false
    }, {
      title: '交易账户',
      width: 75,
      dataIndex: 'tradingAccount',
      ellipsis: true,
      search: false
    }, {
      title: '备注',
      width: 200,
      dataIndex: 'notes',
      ellipsis: true,
      search: false
    }, {
      title: '类型',
      width: 50,
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: {
        1: {
          text: '收入'
        },
        2: {
          text: '支出'
        },
        3: {
          text: '不计入收支'
        },
      },
    }, {
      title: '金额（￥）',
      width: 100,
      dataIndex: 'money',
      search: false
    }, {
      title: '支付方式',
      width: 200,
      dataIndex: 'paymentMethod',
      search: false
    }, {
      title: '交易订单号',
      width: 100,
      dataIndex: 'transactionOrderNumber',
      ellipsis: true,
      copyable: true,
      search: false
    }, {
      title: '商家订单号',
      width: 100,
      copyable: true,
      dataIndex: 'merchantOrderNumber',
      ellipsis: true,

      search: false
    }, {
      title: '支付平台',
      width: 75,
      dataIndex: 'payType',
      valueType: 'select',
      valueEnum: {
        1: {
          text: '支付宝'
        },
        2: {
          text: '微信'
        },
      },
    },
  ];
  const getBillAllData = (opt) => {
    return getBillAll(opt);
  }
  const getTransactionConfigAllData = async () => {
    return getTransactionConfigAll();
  }
  const setTransactionConfigAll = async () => {
    const transactionConfigAllData = await getTransactionConfigAllData();
    if (transactionConfigAllData && transactionConfigAllData.data) {
      let obj = {};
      transactionConfigAllData.data.forEach(item => {
        Object.defineProperty(obj, item.key, {
          // 属性描述符
          configurable: true, // 表示能否通过 delete 删除属性，能否修改属性的特性，默认为 false
          enumerable: true, // 表示该属性是否可枚举，默认为 false
          writable: true, // 表示能否修改属性值，默认为 false
          value: {
            text: item.value
          }, // 当作为数据属性时，表示属性的初始值。如果是访问器属性，则忽略此选项
        })
      })
      console.log(obj);

      setTransactionConfigAllData(obj);
    }
  }
  useEffect(() => {
    // getBillAllData();
    const transactionConfigAllData = getTransactionConfigAllData();
    setTransactionConfigAll();
    // if (transactionConfigAllData && transactionConfigAllData.data) {
    //   let obj = {};
    //   transactionConfigAllData.data.forEach(item => {
    //     Object.defineProperty(obj, item.key, {
    //       // 属性描述符
    //       configurable: true, // 表示能否通过 delete 删除属性，能否修改属性的特性，默认为 false
    //       enumerable: true, // 表示该属性是否可枚举，默认为 false
    //       writable: true, // 表示能否修改属性值，默认为 false
    //       value: item.value, // 当作为数据属性时，表示属性的初始值。如果是访问器属性，则忽略此选项
    //     })
    //   })
    //   console.log(obj);

    //   // setTransactionConfigAllData(transactionConfigAllData.data);
    // }
  }, [])

  return (
    <PageContainer
      header={{
        title: '账单明细',
      }}
    >
      <ProTable<API.UserInfo>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        // toolBarRender={() => [
        //   <Button
        //     key="1"
        //     type="primary"
        //     onClick={() => handleModalVisible(true)}
        //   >
        //     新增
        //   </Button>,
        //   <Button
        //     key="2"
        //     type="primary"
        //     onClick={() => handleModalVisible(true)}
        //   >
        //     微信新增
        //   </Button>,
        //   <Upload {...props}>
        //     <Button key="3"
        //       type="primary">支付宝新增</Button>
        //   </Upload>
        // ]}
        tableExtraRender={(_, data) => (
          <Card>
            <Descriptions size="small">
              <Descriptions.Item label="条数">{data.length}</Descriptions.Item>
              <Descriptions.Item label="支出">
                {sumData.expenditure_total}
              </Descriptions.Item>
              <Descriptions.Item label="收入">
                {sumData.inCome_total}
              </Descriptions.Item>
              <Descriptions.Item label="不计入收支">
                {sumData.not_counting_total}
              </Descriptions.Item>
              <Descriptions.Item label="支付宝总支出">
                {sumData.alipay_expenditure_total}
              </Descriptions.Item>
              <Descriptions.Item label="支付宝总收入">
                {sumData.alipay_income_total}
              </Descriptions.Item>
              <Descriptions.Item label="微信总支出">
                {sumData.wechat_expenditure_total}
              </Descriptions.Item>
              <Descriptions.Item label="微信总收入">
                {sumData.wechat_income_total}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        )}
        request={async (params, sorter, filter) => {
          console.log(params);
          console.log(sorter);
          console.log(filter);
          if (params.transactionTypeValue) {
            params.transactionType = Number(params.transactionTypeValue);
            delete params.transactionTypeValue;
          }
          const { data, code } = await getBillAllData({
            ...params,
            // FIXME: remove @ts-ignore
            // @ts-ignore
            sorter,
            filter,
          });
          setSumData(data.sum);
          return {
            data: data.data,
            success: code === 1 ? true : false,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        scroll={{ x: 1570 }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              let ids = selectedRowsState.map(item => item.id);
              console.log(ids);
              const data = await deleteBill({ ids });
              message.success(data.msg);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
